package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.SimpleConfirmDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.RegisterParams;
import com.isunland.managesystem.entity.SimpleDialogParams;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.SysDistrict;
import com.isunland.managesystem.entity.SysDistrictListOriginal;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SMSContentObserver;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.ImageLineView;
import java.util.Locale;
import java.util.regex.Pattern;
import org.json.JSONException;

/**
 * 对象功能: 注册
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/2/10 10:48
 */

public class RegisterFragment extends BaseFragment {
  public static final String EXTRA_USERNAME =
      RegisterFragment.class.getSimpleName() + "." + "username";
  public static final String EXTRA_PASSWORD =
      RegisterFragment.class.getSimpleName() + "." + "password";
  private static final int REQUEST_SELECT_ADDRESS = 1;

  @BindView(R.id.username) ImageLineView mEtUsername;
  @BindView(R.id.et_password) ImageLineView mEtPassword;
  @BindView(R.id.et_confirmPassword) ImageLineView mEtConfirmPassword;
  @BindView(R.id.et_phone) ImageLineView mEtPhone;
  @BindView(R.id.ilv_company) ImageLineView mIlvCompany;
  @BindView(R.id.ilv_companySimple) ImageLineView mIlvCompanySimple;
  @BindView(R.id.ilv_region) ImageLineView mIlvRegion;
  @BindView(R.id.et_testCode) EditText mEtTestCode;
  @BindView(R.id.tv_testCode) TextView mTvTestCode;
  @BindView(R.id.btn_resetPassword) Button mBtnRegister;
  @BindView(R.id.ll_code) View mLlCode;

  ProgressDialog mDialog;
  //倒计时
  CountDownTimer mTimer;
  @SuppressLint("HandlerLeak") Handler mHandler;
  private RegisterParams mParams;
  private String mCodeDistrict;

  /** 是否注册成功,如果成功,返回上一个页面并回填 */

  @Override public void initData() {
    super.initData();
    mParams =
        mBaseParams instanceof RegisterParams ? (RegisterParams) mBaseParams : new RegisterParams();
    mTimer = new MyCountDownTimer(59000, 1000);
  }

  @Override protected int initLayoutId() {
    return R.layout.fragment_new_register;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(R.string.registe);
    mIlvRegion.setOnClickContentListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //showDialog(AddressSelectDialogFragment.newInstance("0"), REQUEST_SELECT_ADDRESS);
        SimpleTreeListParams params = new SimpleTreeListParams();
        //noinspection unchecked
        params.setItem(new SysDistrict("中国", "100"));
        params.setChildField("code");
        params.setParentField("pcode");
        params.setTitleField("districtName");
        params.setTitle("选择地址");
        params.setClassOriginal(SysDistrictListOriginal.class);
        params.setUrl(ApiConst.URL_QUERY_LIST_ADDRESS);
        params.setParamsNotEmpty(new ParamsNotEmpty().put("pcode", "").put("memberCode", ""));
        BaseVolleyActivity.newInstance(RegisterFragment.this, AddressTreeListActivity.class, params,
            REQUEST_SELECT_ADDRESS);
      }
    });
    mTvTestCode.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        //或缺验证码
        volleyPostTestCode();
      }
    });
    mHandler = new MessageHandler();
    mActivity.getContentResolver()
        .registerContentObserver(Uri.parse("content://sms/"), true,
            new SMSContentObserver(mActivity, mHandler));
    switch (mParams.getRegisterType()) {
      case RegisterParams.TYPE_PERSONAL:
        mBtnRegister.setOnClickListener(new PersonRegisterListener());
        mBtnRegister.setText(R.string.registe);
        mIlvCompany.setVisibility(View.GONE);
        mIlvCompanySimple.setVisibility(View.GONE);
        mIlvRegion.setVisibility(View.GONE);
        break;
      case RegisterParams.TYPE_COMPANY:
        mBtnRegister.setOnClickListener(new CompanyRegisterListener());
        mBtnRegister.setText(R.string.registe);
        break;
      case RegisterParams.TYPE_UPGRADE:
        mBtnRegister.setOnClickListener(new UpgradeRegisterListener());
        mBtnRegister.setText(R.string.personalUserUpdate);
        mEtConfirmPassword.setVisibility(View.GONE);
        mEtPhone.setVisibility(View.GONE);
        mLlCode.setVisibility(View.GONE);
        break;
    }
  }

  private void volleyPostTestCode() {
    if (TextUtils.isEmpty(mEtPhone.getTextContent())) {
      ToastUtil.show("请输入手机号");
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TEST_CODE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("phoneNumber", mEtPhone.getTextContent());
    params.put("isWeiJia", String.valueOf(MyUtils.isWeiJia()));
    mTimer.start();
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
        ToastUtil.show("获取验证码失败");
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            String s1 = successsMessage.getMessage();
            String s2 = new String(s1.getBytes("iso-8859-1"), "UTF-8");
            ToastUtil.show(s2);
          } else {
            ToastUtil.show("获取验证码失败");
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_SELECT_ADDRESS) {

      //mCodeDistrict = data.getStringExtra(AddressSelectDialogFragment.EXTRA_CODE_DISTRICT);
      //mIlvRegion.setTextContent(data.getStringExtra(AddressSelectDialogFragment.EXTRA_NAME));
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      SysDistrict item = ((SysDistrict) params.getItem());
      mCodeDistrict = item == null ? "" : item.getDistrictCode();
      mIlvRegion.setTextContent(params.getFullName());
    }
  }

  private boolean passwordvertify(String mPassword, String mConfirmPassword) {
    if (mPassword == null || mConfirmPassword == null) return false;
    if (mPassword.length() < 6) {
      ToastUtil.show(getString(R.string.passwordLength));
      return false;
    }
    if (!mPassword.equalsIgnoreCase(mConfirmPassword)) {
      ToastUtil.show(getString(R.string.notSamePassword));
      return false;
    }
    return true;
  }

  private boolean companySimpleVertify(String companySimple) {
    if (companySimple == null) return false;

    if (!Pattern.compile("[a-zA-Z]{2,6}").matcher(companySimple).matches()) {
      ToastUtil.show(MyStringUtil.valueOf(mIlvCompanySimple.getViewContent().getHint()));
      return false;
    }
    return true;
  }

  private void showDialogRegister() {
    mDialog = new ProgressDialog(getActivity());
    mDialog.setMessage(getString(R.string.loadingRegister));
    mDialog.setCancelable(true);
    mDialog.show();
  }

  private class PersonRegisterListener implements View.OnClickListener {

    @Override public void onClick(View v) {
      volleyPostRegisterPerson();
    }

    private void volleyPostRegisterPerson() {
      String mUsername = mEtUsername.getTextContent();
      String mPassword = mEtPassword.getTextContent();
      String mPhoneNumber = mEtPhone.getTextContent();
      String mConfirmPassword = mEtConfirmPassword.getTextContent();
      String mRandomCode = mEtTestCode.getText().toString().trim();
      if (!MyStringUtil.isComplete(mUsername, mPassword, mPhoneNumber, mConfirmPassword,
          mRandomCode)) {
        return;
      }

      if (!passwordvertify(mPassword, mConfirmPassword)) return;
      showDialogRegister();
      String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REGISTER_PERSON);
      ParamsNotEmpty params = new ParamsNotEmpty();
      params.put("userName", mUsername);
      params.put("password", mPassword);
      params.put("isWeiJia", String.valueOf(MyUtils.isWeiJia()));
      params.put("phoneNumber", mPhoneNumber);//手机号
      params.put("randomCode", mRandomCode);//短信验证码
      mActivity.volleyPost(url, params.getParams(), new RegisterResponse());
    }
  }

  private class CompanyRegisterListener implements View.OnClickListener {

    @Override public void onClick(View v) {
      volleyPostRegisterCompany();
    }

    private void volleyPostRegisterCompany() {
      String mUsername = mEtUsername.getTextContent();
      String mPassword = mEtPassword.getTextContent();
      String mPhoneNumber = mEtPhone.getTextContent();
      String mConfirmPassword = mEtConfirmPassword.getTextContent();
      String company = mIlvCompany.getTextContent();
      String companySimple = mIlvCompanySimple.getTextContent();
      String region = mIlvRegion.getTextContent();
      String mRandomCode = mEtTestCode.getText().toString().trim();

      if (!MyStringUtil.isComplete(mUsername, mPassword, mConfirmPassword, mPhoneNumber,
          mRandomCode, company, companySimple, region)) {
        return;
      }
      if (!passwordvertify(mPassword, mConfirmPassword)) return;
      if (!companySimpleVertify(companySimple)) return;
      showDialogRegister();

      String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REGISTER_COMPANY);
      ParamsNotEmpty params = new ParamsNotEmpty();
      params.put("userName", mUsername);
      params.put("password", mPassword);
      params.put("isWeiJia", String.valueOf(MyUtils.isWeiJia()));
      params.put("phoneNumber", mPhoneNumber);//手机号
      params.put("randomCode", mRandomCode);//短信验证码
      params.put("memberName", company);
      params.put("memberNameAbb", companySimple);
      params.put("districtCode", mCodeDistrict);
      params.put("districtName", region);
      mActivity.volleyPost(url, params.getParams(), new RegisterResponse());
    }
  }

  private class UpgradeRegisterListener implements View.OnClickListener {

    @Override public void onClick(View v) {
      volleyPostRegisterUpgrade();
    }

    private void volleyPostRegisterUpgrade() {
      String mUsername = mEtUsername.getTextContent();
      String mPassword = mEtPassword.getTextContent();
      String company = mIlvCompany.getTextContent();
      String companySimple = mIlvCompanySimple.getTextContent();
      String region = mIlvRegion.getTextContent();

      if (!MyStringUtil.isComplete(mUsername, mPassword, company, companySimple, region)) return;
      if (!companySimpleVertify(companySimple)) return;
      showDialogRegister();

      String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REGISTER_UPGRADE);
      ParamsNotEmpty params = new ParamsNotEmpty();
      params.put("userName", mUsername);
      params.put("password", mPassword);
      params.put("isWeiJia", String.valueOf(MyUtils.isWeiJia()));
      params.put("memberName", company);
      params.put("memberNameAbb", companySimple);
      params.put("districtCode", mCodeDistrict);
      params.put("districtName", region);
      mActivity.volleyPost(url, params.getParams(), new RegisterResponse());
    }
  }

  private class MyCountDownTimer extends CountDownTimer {
    /**
     * @param millisInFuture The number of millis in the future from the call
     * to {@link #start()} until the countdown is done and {@link #onFinish()}
     * is called.
     * @param countDownInterval The interval along the way to receive
     * {@link #onTick(long)} callbacks.
     */
    MyCountDownTimer(long millisInFuture, long countDownInterval) {
      super(millisInFuture, countDownInterval);
    }

    @Override public void onTick(long time) {
      mTvTestCode.setText(String.format(Locale.CHINA, "%d秒后重发", time / 1000));
      mTvTestCode.setEnabled(false);
    }

    @Override public void onFinish() {
      mTvTestCode.setText("获取验证码");
      mTvTestCode.setEnabled(true);
    }
  }

  private class RegisterResponse extends VolleyResponse {
    @Override public void onVolleyError(VolleyError arg0) {
      mDialog.dismiss();
      ToastUtil.show(getString(R.string.registerFailed));
    }

    @Override public void onVolleyResponse(String arg0) throws JSONException {
      mDialog.dismiss();
      Base result = new Gson().fromJson(arg0, Base.class);
      if (result.getResult() == 1) {
        //设定回传信息
        Intent intent = new Intent();
        intent.putExtra(EXTRA_USERNAME, mEtUsername.getTextContent());
        intent.putExtra(EXTRA_PASSWORD, mEtPassword.getTextContent());
        mActivity.setResult(Activity.RESULT_OK, intent);
      }
      //显示对话框
      SimpleDialogParams params = new SimpleDialogParams();
      params.setMessage(result.getMessage());
      params.setFinishActivityOnDismiss(result.getResult() == 1);
      showDialog(SimpleConfirmDialogFragment.newInstance(params), 0);
    }
  }

  @SuppressLint("HandlerLeak") private class MessageHandler extends Handler {
    @Override public void handleMessage(Message msg) {
      LogUtil.i("msg=" + msg.obj);
      if (msg.what == 1 && null != msg.obj) {
        mEtTestCode.setText(msg.obj.toString());
      }
    }
  }
}
